package com.blacktea.behavioralpatterns.statepattern;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @description: 电梯上下文类
 * @author: black tea
 * @date: 2023/3/26 15:29
 */
@Slf4j
@Component
public class ElevatorContext {

    private final Map<String, ElevatorState> stateMap;

    private ElevatorState state;

    public ElevatorContext(Map<String, ElevatorState> stateMap) {
        this.stateMap = stateMap;
        // 默认状态为closeState
        setState(CloseState.class);
    }

    public void setState(Class<? extends ElevatorState> cls) {
        String simpleName = cls.getSimpleName();
        String mapKey = StrUtil.lowerFirst(simpleName);
        Optional<ElevatorState> stateOptional =
                Optional.ofNullable(stateMap.get(mapKey));
        this.state = stateOptional
                .orElseThrow(()-> ExceptionUtil.wrapRuntime("找不到具体的" + simpleName + "电梯状态类"));
    }

    public void open() {
        state.openDoor();
        setState(OpenState.class);
    }

    public void close() {
        state.closeDoor();
        setState(CloseState.class);
    }

    public void up() {
        state.goUp();
        setState(UpState.class);
    }

    public void down() {
        state.goDown();
        setState(DownState.class);
    }
}
